package net.receiving;

import net.IncomingMessage;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


public class IncomingMessageFactoryImpl implements IncomingMessageFactory {

    private final BlockingQueue<IncomingMessage> queue;

    public IncomingMessageFactoryImpl() {
        queue = new LinkedBlockingQueue<IncomingMessage>();
        final IncomingMessageFactory tcp = new IncomingMessageTCPFactory();
        final IncomingMessageFactory udp = new IncomingMessageUDPFactory();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    queue.offer(tcp.receive());
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    queue.offer(udp.receive());
                }
            }
        }).start();
    }

    public IncomingMessage receive() {
        IncomingMessage res;
        try {
            res = queue.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return res;
    }
}
